<template>
  <div class="app-container">
    <div style="margin: 20px 0 10px 0;">
      <el-form :inline="true" class="search-form" label-width="80px">
        <el-row style="display: flex">
          <div style="flex: 1">
            <el-form-item label="标题" style="margin: 5px 0">
              <el-input class="input-with-select" v-model="searchForm.title" clearable placeholder="请输入标题" />
            </el-form-item>
            <el-form-item label="是否顶置" style="margin: 5px 0">
              <el-select class="input-with-select" v-model="searchForm.is_top" style="width: 100%" placeholder="是否顶置"
                clearable>
                <!-- 1顶置 2不顶置 -->
                <el-option label="顶置" value="1" />
                <el-option label="不顶置" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" style="margin: 5px 0">
              <!-- 状态(1.开启,2.关闭) -->
              <el-select class="input-with-select" v-model="searchForm.status" style="width: 100%" placeholder="状态"
                clearable>
                <!-- 1顶置 2不顶置 -->
                <el-option label="开启" value="1" />
                <el-option label="关闭" value="2" />
              </el-select>
            </el-form-item>
          </div>
          <div style="margin: 5px 0">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="doSearch">搜索</el-button>
              <el-button type="primary" icon="el-icon-refresh" @click="doCancelSearch">重置</el-button>
            </el-form-item>
          </div>
        </el-row>
      </el-form>
    </div>
    <el-divider></el-divider>
    <div class="marginTop">
      <el-row :gutter="20">
        <el-col :span="20">
          <el-button type="primary" size="small" @click="addclassification()"
            icon="el-icon-circle-plus-outline">添加分类</el-button>
          <el-button type="primary" size="small" @click="addactice()"
            icon="el-icon-circle-plus-outline">添加公告</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col class="marginTop">
          <el-table :header-cell-style="{
              'background-color': '#f3f8fe',
              color: '#606266',
              height: '50px',
            }" v-loading="isLoading" :data="afficheList">
            <el-table-column fixed="left" label="ID" prop="id" align="center" />
            <el-table-column label="标题" prop="title" align="center">
              <template slot-scope="scope">
            <el-tooltip placement="top-start" :content="scope.row.title + ''">
              <div class="one_line_hidden">
                {{ scope.row.title ? scope.row.title : "-" }}
              </div>
            </el-tooltip>
            </template>
             </el-table-column>
            <el-table-column label="状态" align="center">
              <template slot-scope="scope">
                <div v-if="scope.row.status == 1">展示</div>
                <div v-else>隐藏</div>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="created_at" align="center" />
            <el-table-column label="覆盖地区" align="center">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :content="
                        scope.row.cover_region_names
                          ? scope.row.cover_region_names.toString()
                          : ''
                      " placement="top">
                  <div v-if="
                          scope.row.cover_region_names
                            ? scope.row.cover_region_names.length !== 0
                            : false
                        " style="display: flex; justify-content: center">
                    <div v-if="index < 3" v-for="(item, index) in scope.row.cover_region_names
                            ? scope.row.cover_region_names
                            : []" :key="index">
                      {{ item }}
                    </div>
                    <div v-if="
                            scope.row.cover_region_names
                              ? scope.row.cover_region_names.length > 3
                              : false
                          " class="table-num">
                      + {{ scope.row.cover_region_names.length }}
                    </div>
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="覆盖分组" align="center">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark"
                  :content="scope.row.cover_group_names ? scope.row.cover_group_names.join('/'): ''" placement="top">
                  <div v-if="
                          scope.row.cover_group_names
                            ? scope.row.cover_group_names.length !== 0
                            : false
                        " style="display: flex; justify-content: center">
                    <div v-if="index < 3" v-for="(item, index) in scope.row.cover_group_names" :key="index">
                      {{ item }}
                    </div>
                    <div v-if="scope.row.cover_group_names.length > 3" class="table-num">
                      + {{ scope.row.cover_group_names.length }}
                    </div>
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column fixed="right" width="180" prop="address" label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="goUpdateAffiche(scope.row.id)">
                  编辑
                </el-button>
                <el-divider direction="vertical"></el-divider>
                <el-button type="text" @click="doDeleteAffice(scope.row.id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col style="margin-top: 20px; text-align: right">
          <el-pagination :current-page.sync="paginationObj.start" :page-sizes="paginationObj.pageSizes"
            :page-size="paginationObj.limit" layout="total, sizes, prev, pager, next, jumper"
            :total="paginationObj.total" background @size-change="sizeChange" @current-change="currentChange" />
        </el-col>
      </el-row>
    </div>

    <!-- 公告弹窗 -->
    <el-drawer :modal-append-to-body="false" :append-to-body="true" title="添加公告" size="70%"
      :withHeader="false" :visible.sync="drawerShow" @close="doCancelAddOrUpdateAffice" :show-close="true">
      <div style="position: relative;margin-bottom: 30px;">
        <div class="drawerTitle">
          <span>{{afficheForm.id ? '修改公告' : '添加公告'}}</span>
          <div class="close" @click="doCancelAddOrUpdateAffice">
            <i class="el-icon-close" style="font-size: 24px;"></i>
          </div>
        </div>
      </div>
      <div>
        <el-scrollbar wrap-style="overflow-x:hidden;" style="height: calc(100vh - 160px)">
          <el-form ref="afficheFormRef" :model="afficheForm" :rules="afficheFormRules" label-width="120px"
            :inline="false">
            <el-row>
              <el-col :span="11">
                <el-form-item label="公告标题" prop="title">
                  <el-input placeholder="请填写标题" v-model="afficheForm.title" />
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="公告排序" prop="weight">
                  <el-input placeholder="请填写排序" v-model="afficheForm.weight" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="11">
                <el-form-item label="覆盖地区" prop="address">
                  <el-cascader filterable v-model="afficheForm.cover_region_json" style="width: 90%"
                    :options="addressList" collapse-tags :props="{
                      multiple: true,
                      value: 'id',
                      label: 'name',
                      children: 'children',
                      checkStrictly: true,
                    }" clearable></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="覆盖分组" prop="address">
                  <el-select v-model="afficheForm.cover_group_ids" multiple clearable collapse-tags
                    placeholder="请选用户分组">
                    <el-option v-for="item in groupingList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="11">
                <el-form-item label="展示状态" prop="status">

                  <el-select v-model="afficheForm.status" placeholder="请选择" clearable>
                    <el-option label="开启" :value="1" />
                    <el-option label="关闭" :value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="顶置状态" prop="is_top">

                  <el-select v-model="afficheForm.is_top" placeholder="请选择" clearable>
                    <el-option label="顶置" :value="1" />
                    <el-option label="不顶置" :value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="20">
                <el-form-item label="公告内容" prop="content">
                  <div>
                    <editor-text
                      v-model="afficheForm.content"
                      :height="360"
                      @input="editorclick"
                    />
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-scrollbar>
        <el-col :span="24" style="text-align: right;padding-right:30px">
          <el-button @click="doCancelAddOrUpdateAffice">取消</el-button>
          <el-button :loading="submitLoadings" type="primary" @click="doSaveAffice()">保存</el-button>
        </el-col>
      </div>
    </el-drawer>
    <!--  -->
    <el-dialog title="增加分类" :visible.sync="dialogClass" width="600px" :before-close="CloseDialogLabel">
      <el-row :gutter="20">
        <el-form :model="ruleFormClass" status-icon :rules="rulesClass" ref="rulesClass" label-width="100px"
          class="demo-ruleForm">
          <el-col :span="22">
            <el-form-item label="分类名称" prop="name">
              <el-input type="text" v-model="ruleFormClass.name" maxlength="10" clearable show-word-limit
                 placeholder="请输入分类名称"
                autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="CloseDialogLabel">取 消</el-button>
        <el-button type="primary" :loading="butloading" @click="submitFormClass('rulesClass')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {
    getAfficheList,
    SaveAffiche,
    delAffiche
  } from "@/api/admin/affiche";
  import {
    getgroupList,
    getRegionList
  } from "@/api/user/index";
  import mix from "@/mixins/index";
  import TinymceEditor from '@/components/Tinymce'
  export default {
    name: "AfficheList",
    components: {
      TinymceEditor
    },
    mixins: [mix],
    data() {
      return {
        isLoading: false, // 公告列表是否正在加载
        searchForm: {},
        afficheList: [], // 公告列表
        afficheForm: {
          id: "",
        },
        afficheFormRules: {
          title: [{
            required: true,
            message: "标题必填！",
            trigger: "blur"
          }],
          status: [{
            required: true,
            message: "请选择展示状态！",
            trigger: "blur"
          }, ],
          address: [{
            required: false,
            message: "地址必填！",
            trigger: "blur"
          }],
          is_top: [{
            required: false,
            message: "是否置顶必填！",
            trigger: "blur"
          }, ],
          content: [{
            required: true,
            message: "内容必填！",
            trigger: "blur"
          }],
        },
        addressList: [], // 省市区
        props: {
          label: "name",
          value: "id",
        },
        groupingList: [], //用户分组列表
        drawerShow: false, //弹窗展示
        submitLoadings: false, //提交状态
        dialogClass:false,
        butloading:false,
        ruleFormClass: {
          name: "",
        },
        rulesClass: {
          name: [{
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error("分类名称不能为空"));
              }
              callback();
            },
            trigger: "blur",
          }, ],
        },
      };
    },
    created() {
      this.getAfficheListData();
      this.getRegionListData();
      this.getUserGroupList();
    },
    methods: {
      //添加分类
      submitFormClass(formName) {
        var _this = this;
        _this.$refs[formName].validate((valid) => {
          if (valid) {
            _this.butloading = true
            // addtagCategory(_this.ruleFormClass).then((res) => {
            //   if (res.code !== 200) {
            //     _this.$messages.error(res.msg);
            //     _this.butloading = false
            //     return;
            //   }
            //   _this.$messages.success("操作成功");
            //   _this.dialogClass = false;
            //   _this.butloading = true
            //   this.ruleFormClass.name = ''
            // });
          } else {
            return false;
          }
        });
      },
      // 关闭弹框
      CloseDialogLabel() {
        this.dialogClass = false;
        this.ruleFormClass.name = ''
      },
      //新增分类
      addclassification(){
        this.dialogClass = true;
      },
      addactice(){
        this.afficheForm.id = ''
        this.afficheForm.content = ''
        this.drawerShow = true
      },
      // 商品详情回调
      editorclick(e) {
        this.afficheForm.content = e;
      },
      // 获取城市信息
      getRegionListData() {
        if (localStorage.getItem("region")) {
          let regions = JSON.parse(localStorage.getItem("region"));
          this.addressList = regions;
        }else{
          getRegionList().then((res) => {
            if (res.code === 200) {
              this.addressList = res.data;
            } else {
              this.$message.error(res.message);
            }
          });
        }
      },
      //获取列表
      async getAfficheListData() {
        this.isLoading = true;
        this.searchForm.page = this.paginationObj.start;
        this.searchForm.count = this.paginationObj.limit;
        const res = await getAfficheList(this.searchForm);
        const {
          code,
          data,
          msg
        } = res;
        if (code === 200) {
          this.afficheList = data.list;
          this.paginationObj.total = data.total;
        } else {
          this.$message.error(msg);
        }
        this.isLoading = false;
      },

      resetPaginationObj() {
        this.paginationObj.start = 1;
        this.paginationObj.limit = 10;
      },
      // 查询公告列表
      doSearch() {
        this.paginationObj.start = 1;
        this.getAfficheListData();
      },
      // 取消搜索
      doCancelSearch() {
        this.searchForm = this.$options.data().searchForm;
        this.paginationObj.start = 1;
        this.getAfficheListData();
      },
      sizeChange(val) {
        this.paginationObj.start = 1;
        this.paginationObj.limit = val;
        this.getAfficheListData();
      },
      currentChange(val) {
        this.paginationObj.start = val;
        this.getAfficheListData();
      },

      // 去修改公告
      goUpdateAffiche(id) {
        this.drawerShow = true;
        const item = this.afficheList.find((item) => item.id === id);
        if (item) {
          this.afficheForm = item;
        }
      },
      // 删除公告
      doDeleteAffice(id) {
        this.$confirm("此操作将删除该公告, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(async () => {
            const res = await delAffiche({
              id
            });
            const {
              code,
              msg
            } = res;
            if (code === 200) {
              this.$message.success("删除成功！");
              // 更新列表
              this.getAfficheListData();
            } else {
              this.$message.error(msg);
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      },

      // 取消新增或更新公告
      doCancelAddOrUpdateAffice() {
        this.drawerShow = false;
        this.afficheForm = this.$options.data().afficheForm;
      },

      //表单提交
      doSaveAffice() {
        this.$refs.afficheFormRef.validate(async (valid) => {
          if (valid) {
            // this.afficheForm.province_id = this.afficheForm.address[0];
            // this.afficheForm.city_id = this.afficheForm.address[1];
            // this.afficheForm.county_id = this.afficheForm.address[2];
            // delete this.afficheForm.address;
            this.submitLoadings = true;
            console.log("this.afficheForm", this.afficheForm);
            // 添加或者更新公告
            const res = await SaveAffiche({
              id: this.afficheForm.id,
              title: this.afficheForm.title,
              content: this.afficheForm.content,
              weight: this.afficheForm.weight,
              is_top: this.afficheForm.is_top,
              status: this.afficheForm.status,
              cover_group_ids: this.afficheForm.cover_group_ids.join(','),
              cover_region_json: JSON.stringify(this.afficheForm.cover_region_json),
            });
            const {
              code,
              msg
            } = res;
            if (code === 200) {
              this.submitLoadings = false;
              const str = this.afficheForm.id ? "修改成功!" : "添加成功!";
              this.$message.success(str);
              // 关闭对话框并更新数据
              this.drawerShow = false;
              this.afficheForm = this.$options.data().afficheForm;
              this.getAfficheListData();
            } else {
              this.submitLoadings = false;
              this.$message.error(msg);
            }
          } else {
            this.$message.warning("请检查：有部分信息尚未添加完整！");
          }
        });
      },

      //获取分组列表
      getUserGroupList() {
        getgroupList().then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            return;
          }
          this.groupingList = res.data.list;
        });
      },
    },
  };
</script>
<style lang='scss' scoped>
  .margin-10 {
    margin: 10px;
  }
</style>
